<?php
/**
 * Created by PhpStorm.
 * User: guokunsheng
 * Date: 2021/10/18
 * Time: 上午11:15
 */

namespace app\test\controller;

use think\Controller;

/**
 * 通过城市名称查询经纬度
 * Class Geo
 * @doc https://lbs.amap.com/api/webservice/guide/api/georegeo
 * @package app\test\controller
 */
class Geo extends Controller
{
    /**
     * @date 2021-10-18 11:30
     * @account imatch@goddessxzns.com
     * @application zhunle
     * @keyname address
     * @support Web服务
     * @return  &output=JSON 默认返回JSON，可选XML
     * @var string
     */
    private $apiAddress = 'https://restapi.amap.com/v3/geocode/geo?key=51676375317998bfc34465eb5ac3eae5';

    public function index()
    {
        $addrName = trim(input('addr/s', ''));
//        if ($addrName === '')
//        {
//            return show(200, '地址不能为空', []);
//        }
        echo '<form method="get" action="/test/geo/index">
                <input type="text" name="addr" value="' . $addrName . '">  
                <input type="submit" value="提交">
              </form>';

        $data = '';

        $res = [];

        if ($addrName)
        {
            $data = file_get_contents($this->apiAddress . '&address=' . $addrName);
        }

        if ($data !== '')
        {
            $data = json_decode($data, true);

            if ($data['count'] >= 1)
            {
                foreach ($data['geocodes'] as $k => $v)
                {
                    $parseData = $this->floatDegToString($v['location']);
                    $tmp = [
                        'formatted_address' => $v['formatted_address'],
                        'country' => $v['country'],
                        'province' => $v['province'],
                        'city' => $v['city'],
                        'district' => $v['district'],
                        'citycode' => $v['citycode'],
                        'adcode' => $v['adcode'],
                        'level' => $v['level'],
                        'location' => $v['location'],
                        'json_data' => [
                            'value' => $v['adcode'],
                            'text' => $v['district'],
                            'long_deg' => $parseData['long_deg'],
                            'long_min' => $parseData['long_min'],
                            'ew' => $parseData['long_deg'] >= 0 ? 1 : -1,
                            'lat_deg' => $parseData['lat_deg'],
                            'lat_min' => $parseData['lat_min'],
                            'ns' => $parseData['lat_deg'] >= 0 ? 1 : -1,
                        ],
                    ];
//                    $res[] = array_merge($tmp, $parseData);
                    $res[] = $tmp;
                }
            }
        }
        echo '<pre>';
        print_r($res);
//        return show(200, '请求成功', $res);
    }

    public function floatDegToString(string $deg)
    {
        $arr = explode(',', $deg);
        $long = (float)$arr[0];
        $lat = (float)$arr[1];

        $longDeg = (int)$long;
        $longMin = ceil(($long - $longDeg) * 60);
        $ew = $long > 0 ? 1 : -1;
        if ($longMin >= 60)
        {
            $longMin = 59;
        } elseif ($longMin < 10)
        {
            $longMin = '0' . $longMin;
        }

        $latDeg = (int)$lat;
        $latMin = ceil(($lat - $latDeg) * 60);
        $ns = $lat > 0 ? 1 : -1;
        if ($latMin >= 60)
        {
            $latMin = 59;
        } elseif ($latMin < 10)
        {
            $latMin = '0' . $latMin;
        }

        return ['longitude' => $long, 'latitude' => $lat, 'long_deg' => $longDeg, 'long_min' => $longMin, 'ew' => $ew, 'lat_deg' => $latDeg, 'lat_min' => $latMin, 'ns' => $ns];
    }

    public function getAllCities()
    {
        /**
         * 高德api文档地址：
         * https://lbs.amap.com/api/webservice/guide/api/district
         * APIkey：51676375317998bfc34465eb5ac3eae5
         */
        $allData = file_get_contents('https://restapi.amap.com/v3/config/district?subdistrict=3&key=51676375317998bfc34465eb5ac3eae5');

        $china = json_decode($allData, true)['districts'][0];

        $chinaCities = $china['districts'];

        $chinaCities = resort($chinaCities, 'adcode', 'ASC');

        $data = [];

        foreach ($chinaCities as $k1 => $v1)
        {
            $province = [
                'value' => (int)$v1['adcode'],
                'text' => $v1['name'],
                'children' => []
            ];
            if ($v1['name'] === '台湾省')
            {
                // 由于高德地图暂不支持台湾省行政区划查询，此处自行定义
                $province['children'] = [
                    [
                        'value' => '710000',
                        'text' => '台湾',
                        'children' => [
                            [
                                'value' => '680101',
                                'text' => '台北市',
                                'long_deg' => 121,
                                'long_min' => 34,
                                'ew' => 1,
                                'lat_deg' => 25,
                                'lat_min' => '02',
                                'ns' => 1
                            ],
                            [
                                'value' => '680102',
                                'text' => '高雄市',
                                'long_deg' => 120,
                                'long_min' => 19,
                                'ew' => 1,
                                'lat_deg' => 22,
                                'lat_min' => 37,
                                'ns' => 1
                            ],
                            [
                                'value' => '680103',
                                'text' => '基隆市',
                                'long_deg' => 121,
                                'long_min' => 45,
                                'ew' => 1,
                                'lat_deg' => 25,
                                'lat_min' => '08',
                                'ns' => 1
                            ],
                            [
                                'value' => '680104',
                                'text' => '台中市',
                                'long_deg' => 120,
                                'long_min' => 39,
                                'ew' => 1,
                                'lat_deg' => 24,
                                'lat_min' => '09',
                                'ns' => 1
                            ],
                            [
                                'value' => '680105',
                                'text' => '台南市',
                                'long_deg' => 120,
                                'long_min' => 11,
                                'ew' => 1,
                                'lat_deg' => 22,
                                'lat_min' => 59,
                                'ns' => 1
                            ],
                            [
                                'value' => '680106',
                                'text' => '新竹市',
                                'long_deg' => 120,
                                'long_min' => 58,
                                'ew' => 1,
                                'lat_deg' => 24,
                                'lat_min' => 48,
                                'ns' => 1
                            ],
                            [
                                'value' => '680107',
                                'text' => '嘉义市',
                                'long_deg' => 120,
                                'long_min' => 28,
                                'ew' => 1,
                                'lat_deg' => 23,
                                'lat_min' => 29,
                                'ns' => 1
                            ],
                            [
                                'value' => '680108',
                                'text' => '台北县',
                                'long_deg' => 121,
                                'long_min' => 34,
                                'ew' => 1,
                                'lat_deg' => 25,
                                'lat_min' => '02',
                                'ns' => 1
                            ],
                            [
                                'value' => '680109',
                                'text' => '宜兰县',
                                'long_deg' => 121,
                                'long_min' => 46,
                                'ew' => 1,
                                'lat_deg' => 24,
                                'lat_min' => 44,
                                'ns' => 1
                            ],
                            [
                                'value' => '680110',
                                'text' => '新竹县',
                                'long_deg' => 121,
                                'long_min' => '01',
                                'ew' => 1,
                                'lat_deg' => 24,
                                'lat_min' => 49,
                                'ns' => 1
                            ],
                            [
                                'value' => '680111',
                                'text' => '桃园县',
                                'long_deg' => 121,
                                'long_min' => 18,
                                'ew' => 1,
                                'lat_deg' => 24,
                                'lat_min' => 59,
                                'ns' => 1
                            ],
                            [
                                'value' => '680112',
                                'text' => '苗栗县',
                                'long_deg' => 120,
                                'long_min' => 49,
                                'ew' => 1,
                                'lat_deg' => 24,
                                'lat_min' => 34,
                                'ns' => 1
                            ],
                            [
                                'value' => '680113',
                                'text' => '台中县',
                                'long_deg' => 120,
                                'long_min' => 39,
                                'ew' => 1,
                                'lat_deg' => 24,
                                'lat_min' => '09',
                                'ns' => 1
                            ],
                            [
                                'value' => '680114',
                                'text' => '彰化县',
                                'long_deg' => 120,
                                'long_min' => 33,
                                'ew' => 1,
                                'lat_deg' => 24,
                                'lat_min' => '04',
                                'ns' => 1
                            ],
                            [
                                'value' => '680115',
                                'text' => '南投县',
                                'long_deg' => 120,
                                'long_min' => 42,
                                'ew' => 1,
                                'lat_deg' => 23,
                                'lat_min' => 54,
                                'ns' => 1
                            ],
                            [
                                'value' => '680116',
                                'text' => '嘉义县',
                                'long_deg' => 120,
                                'long_min' => 18,
                                'ew' => 1,
                                'lat_deg' => 23,
                                'lat_min' => 27,
                                'ns' => 1
                            ],
                            [
                                'value' => '680117',
                                'text' => '云林县',
                                'long_deg' => 120,
                                'long_min' => 32,
                                'ew' => 1,
                                'lat_deg' => 23,
                                'lat_min' => 41,
                                'ns' => 1
                            ],
                            [
                                'value' => '680118',
                                'text' => '台南县',
                                'long_deg' => 120,
                                'long_min' => 11,
                                'ew' => 1,
                                'lat_deg' => 22,
                                'lat_min' => 59,
                                'ns' => 1
                            ],
                            [
                                'value' => '680119',
                                'text' => '高雄县',
                                'long_deg' => 120,
                                'long_min' => 19,
                                'ew' => 1,
                                'lat_deg' => 22,
                                'lat_min' => 37,
                                'ns' => 1
                            ],
                            [
                                'value' => '680120',
                                'text' => '屏东县',
                                'long_deg' => 120,
                                'long_min' => 30,
                                'ew' => 1,
                                'lat_deg' => 22,
                                'lat_min' => 40,
                                'ns' => 1
                            ],
                            [
                                'value' => '680121',
                                'text' => '台东县',
                                'long_deg' => 121,
                                'long_min' => '09',
                                'ew' => 1,
                                'lat_deg' => 22,
                                'lat_min' => 45,
                                'ns' => 1
                            ],
                            [
                                'value' => '680122',
                                'text' => '花莲县',
                                'long_deg' => 121,
                                'long_min' => 37,
                                'ew' => 1,
                                'lat_deg' => 23,
                                'lat_min' => 59,
                                'ns' => 1
                            ],
                            [
                                'value' => '680123',
                                'text' => '澎湖县',
                                'long_deg' => 119,
                                'long_min' => 34,
                                'ew' => 1,
                                'lat_deg' => 23,
                                'lat_min' => 34,
                                'ns' => 1
                            ]
                        ]
                    ]
                ];
            } else
            {
                foreach ($v1['districts'] as $k2 => $v2)
                {
                    if (in_array($v1['name'], ['香港特别行政区', '澳门特别行政区'], true))
                    {
                        if (!isset($province['children'][0]))
                        {
                            $province['children'][] = [
                                'value' => (int)$v1['adcode'],
                                'text' => mb_substr($v1['name'], 0, 2),
                                'children' => []
                            ];
                        }
                        $longlat = $this->floatDegToString($v2['center']);
                        $area = [
                            'value' => (int)$v2['adcode'],
                            'text' => $v2['name'],
                            'long_deg' => $longlat['long_deg'],
                            'long_min' => $longlat['long_min'],
                            'ew' => $longlat['ew'],
                            'lat_deg' => $longlat['lat_deg'],
                            'lat_min' => $longlat['lat_min'],
                            'ns' => $longlat['ns']
                        ];
                        $province['children'][0]['children'][] = $area;
                    } else
                    {
                        $city = [
                            'value' => (int)$v2['adcode'],
                            'text' => $v2['name'],
                            'children' => []
                        ];
                        foreach ($v2['districts'] as $k3 => $v3)
                        {
                            $longlat = $this->floatDegToString($v3['center']);
                            $area = [
                                'value' => (int)$v3['adcode'],
                                'text' => $v3['name'],
                                'long_deg' => $longlat['long_deg'],
                                'long_min' => $longlat['long_min'],
                                'ew' => $longlat['ew'],
                                'lat_deg' => $longlat['lat_deg'],
                                'lat_min' => $longlat['lat_min'],
                                'ns' => $longlat['ns']
                            ];
                            $city['children'][] = $area;
                        }
                        switch ($city['text'])
                        {
                            case '北京城区':
                                $city['text'] = '北京市';
                                break;
                            case '天津城区':
                                $city['text'] = '天津市';
                                break;
                            case '上海城区':
                                $city['text'] = '上海市';
                                break;
                            case '重庆郊县':
                            case '重庆城区':
                                $city['text'] = '重庆市';
                                break;
                        }

                        $city['children'] = resort($city['children'], 'value', 'ASC');

                        $province['children'][] = $city;
                    }
                }
            }
            $province['children'] = resort($province['children'], 'value', 'ASC');
            $data[] = $province;
        }

        echo json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
    }

    /**
     * 地址库计算经纬度，更新本地文件
     */
    public function getTimezoneByJsonFile()
    {
        $fileData = json_decode(file_get_contents(ROOT_PATH . 'XZNSLocationDataInfo-bak.json'), JSON_BIGINT_AS_STRING | JSON_OBJECT_AS_ARRAY);

        foreach ($fileData as $k1 => $v1)
        {
            $fileData[$k1]['value'] = (string)$v1['value'];
            if (!empty($v1['children']))
            {
                foreach ($v1['children'] as $k2 => $v2)
                {
                    $fileData[$k1]['children'][$k2]['value'] = (string)$v2['value'];
                    if (!empty($v2['children']))
                    {
                        foreach ($v2['children'] as $k3 => $v3)
                        {
                            $fileData[$k1]['children'][$k2]['children'][$k3]['value'] = (string)$v3['value'];
                            $fileData[$k1]['children'][$k2]['children'][$k3]['timezone'] = 8;
                            // 国外地区时区根据经纬度进行计算
                            if (in_array($v1['text'], ['北美洲', '大洋洲', '非洲', '南美洲', '欧洲', '亚洲'], true))
                            {
                                $timezone = (int)(($v3['long_deg'] + $v3['long_min'] / 60) / 15) * $v3['ew'];
                                $ys = ($v3['long_deg'] + $v3['long_min'] / 60) % 15;
                                if ($ys <= 7.5)
                                {
                                    $fileData[$k1]['children'][$k2]['children'][$k3]['timezone'] = $timezone;
                                } else
                                {
                                    // ew=>1东经  ew=>-1西经
                                    $fileData[$k1]['children'][$k2]['children'][$k3]['timezone'] = $timezone + ($v3['ew'] > 0 ? 1 : -1);
                                }
                            }
                        }
                    }
                }
            }
        }

        file_put_contents(ROOT_PATH . 'XZNSLocationDataInfo.json', json_encode($fileData, JSON_NUMERIC_CHECK | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT | JSON_BIGINT_AS_STRING));
    }
}
